import { h } from 'vue'
import { defineStore } from 'pinia'
import type { ErrorMessageMode } from '@/types/axios'

import { store } from '@/store'
import { router } from '@/router'
import { PageEnum } from '@/enums/pageEnum'
import { ACCESS_TOKEN_KEY, USER_INFO_KEY } from '@/enums/cacheEnum'
import { useMessage } from '@/hooks/web/useMessage'
import { indexApi } from '@/api/sys/indexApi'
import type { EmployeeInfoResp, LoginReq } from '@/model/sys/indexModel'
import { clearCache, getAccessToken, getCache, removeCache, setCache } from '@/utils/cache'

interface UserState {
  userInfo: Nullable<EmployeeInfoResp>
  hasSet: boolean
  accessToken?: string
  sessionTimeout?: boolean
}

export const useUserStore = defineStore('app-user', {
  state: (): UserState => ({
    // user info
    userInfo: null,
    hasSet: false,
    // token
    accessToken: undefined,
    // Whether the login expired
    sessionTimeout: false,
  }),
  getters: {
    getUserInfo(state): EmployeeInfoResp {
      return (state.userInfo ?? getCache<EmployeeInfoResp>(USER_INFO_KEY)) || {}
    },
    getAccessToken(state): string {
      return state.accessToken ?? getAccessToken()
    },
    getSessionTimeout(state): boolean {
      return !!state.sessionTimeout
    },
  },
  actions: {
    setAccessToken(info: string | undefined) {
      this.accessToken = info ?? '' // for null
      setCache(ACCESS_TOKEN_KEY, info)
    },
    setUserInfo(info: EmployeeInfoResp | null) {
      if (!this.hasSet) {
        this.userInfo = info
        setCache(USER_INFO_KEY, info)
        this.hasSet = true
      }
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag
    },
    resetState() {
      this.userInfo = null
      this.hasSet = false
      this.accessToken = ''
      this.sessionTimeout = false
      removeCache(ACCESS_TOKEN_KEY)
      removeCache(USER_INFO_KEY)
    },
    /**
     * @description: login
     */
    async login(
      params: LoginReq & {
        goHome?: boolean
        mode?: ErrorMessageMode
      },
    ): Promise<EmployeeInfoResp | null> {
      try {
        const { goHome = true, mode, ...loginParams } = params
        const data = await indexApi.login(loginParams, mode)
        const { accessToken } = data

        // save token
        this.setAccessToken(accessToken)
        return this.afterLoginAction(goHome)
      }
      catch (error) {
        return Promise.reject(error)
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<EmployeeInfoResp | null> {
      if (!this.getAccessToken) {
        return null
      }
      // get user info
      const userInfo = await this.getUserInfoAction()

      const sessionTimeout = this.sessionTimeout
      if (sessionTimeout) {
        this.setSessionTimeout(false)
      }
      else {
        // eslint-disable-next-line ts/no-unused-expressions
        goHome && (await router.replace(PageEnum.BASE_HOME))
      }
      return userInfo
    },
    async getUserInfoAction(): Promise<EmployeeInfoResp | null> {
      if (!this.getAccessToken)
        return null
      const userInfo = await indexApi.info()
      this.setUserInfo(userInfo)
      return userInfo
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getAccessToken) {
        try {
          await indexApi.logout()
        }
        catch {
          console.log('注销Token失败')
        }
      }
      this.resetState()
      clearCache()
      // eslint-disable-next-line ts/no-unused-expressions
      goLogin && router.push(PageEnum.BASE_LOGIN)
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage()
      createConfirm({
        iconType: 'warning',
        title: () => h('span', '温馨提醒'),
        content: () => h('span', '是否确认退出系统'),
        onOk: async () => {
          await this.logout(true)
        },
      })
    },
  },
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store)
}
